# -*- coding: utf-8 -*-

import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time,xbmcaddon

##General vars
__plugin__ = "nana10"
__author__ = "Shmulik"
__USERAGENT__ = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
__XBMC_Revision__ = ""


"""
TODO:
# Shows like Halayla of Lior Schleien doesn't list full episode on vod.nana10, but in schleien.nana10.co.il does
"""

def getMatches(url,pattern,clear=False):
  data = getData(url)
  if (clear):
    data = data.replace("\n","").replace("\t","").replace("\r","")
  matches=re.compile(pattern).findall(data)
  return matches

def getData(url):
  cachePath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','pages',urllib.quote(url,"") ))
  if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= 1):
    print("loading from cache...  "+url)
    f = open(cachePath, 'r')
    ret = f.read()
    f.close()
    return ret
  print("loading...  "+url)
  req = urllib2.Request(url)
  req.add_header('User-Agent', __USERAGENT__)
  response = urllib2.urlopen(req)
  data=response.read()
  response.close()
  f = open(cachePath, 'w')
  f.write(data)
  f.close()
  
  return data
  
  
def getCategoryList():
  matches = getMatches("http://10tv.nana10.co.il/Category/?CategoryID=400008",'<div class="t1384_Menu" onclick="t1384\.openSubMenu\((\d+),this\);return false;".*?>(.*?)</div>')
  for id,name in matches:
    u=sys.argv[0]+"?mode=1&name="+urllib.quote_plus(name)+"&url="+id
    li=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    li.setInfo( type="Video", infoLabels={ "Genre":name } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)
  #Add "Live Tv" Button  
  u=sys.argv[0]+"?mode=10"
  li=xbmcgui.ListItem("Live TV")
  li.setInfo( type="Video",infoLabels={"Title":"Live Tv"} )
  xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li)



def getSeriesList():

  addon = xbmcaddon.Addon( id=os.path.basename( os.getcwd() ) )
  
  data = getMatches("http://10tv.nana10.co.il/Category/?CategoryID=400008",'<div id="t1384SubMenu'+url+'" class="t1384_SubMenuContainer">(.*?)</div>')[0]
  matches = re.compile('<a sectionid="(\d+)".*?>(.*?)</a>').findall(data)
  
  manualsSeries = {'1':[('11586','לרדת בגדול עונה 4')],'5':[('2632','לונדון את קירשנבאום'),('2171','חמש עם רפי רשף')],'6':[('10235','בריאות 10'),('10162','המקצוענים')]}
  if (url in manualsSeries):
    matches+=manualsSeries[url]
  
  
  for id,name in matches:
    u=sys.argv[0]+"?mode=2&name="+urllib.quote_plus(name)+"&url="+id
    
    icnpath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','icons',name.replace('"','')+".png") ) 
    
    if addon.getSetting( "use_icons" )=="true" and os.path.exists(icnpath):
      icon = icnpath
    else:
      icon = "DefaultVideo.png"
    
    hdrpath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','headers',name.replace('"','')+".png") ) 
    if addon.getSetting( "use_headers" )=="true" and os.path.exists(hdrpath):
      header = hdrpath
    else:
      header = icon
        
    li=xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=header)
    li.setInfo( type="Video", infoLabels={ "TVShowTitle ":name } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)
  xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
       
def getEpisodeList(url):
  pat = '"CreatedDateFormated":"(.*?)","Title":"(.*?)","SubTitle":"(.*?)","ThumbPicPath":"(.*?)","PicPath":"(.*?)","VideoID":"(.*?)"'
  matches = getMatches('http://common.nana10.co.il/SectionVOD/GetSectionVOD.ashx?PageSize=150&FetchVideo=1&PageNumber=1&&SectionID='+url,pat)
  
  for date,title,sub,thumb,pic,id in matches :
    u=sys.argv[0]+"?url="+id+"&mode=3"
    liz=xbmcgui.ListItem(label=title, label2=sub, iconImage="http://f.nanafiles.co.il/"+thumb, thumbnailImage="http://f.nanafiles.co.il/"+pic)
    liz.setInfo( type="Video", infoLabels={ "Title": title,"Tagline":sub,"Date":date} )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
  xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
  
"""
  d = getData("http://common.nana10.co.il/SectionVOD/GetSectionVOD.ashx?PageSize=150&FetchVideo=1&PageNumber=1&&SectionID=10534")[1:-2]
  jsonO = json.loads(d)["HeadlineList"]
  
  
  for video in jsonO :
    u=sys.argv[0]+"?url="+video["VideoID"]+"&mode=3"
    liz=xbmcgui.ListItem(label=video["Title"],label2=video["SubTitle"], iconImage="http://f.nanafiles.co.il/"+video["ThumbPicPath"], thumbnailImage="http://f.nanafiles.co.il/"+video["PicPath"])
    liz.setInfo( type="Video", infoLabels={ "Title": video["Title"],"Tagline":video["SubTitle"],"Date":video["CreatedDateFormated"]} )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
  xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
"""

def getCookie(url,cookiename):
  req = urllib2.Request(url)
  req.add_header('User-Agent',__USERAGENT__)
  response = urllib2.urlopen(req)
  cooks=response.headers["set-cookie"].split(";")
  for x in cooks:
    y = x.split("=")
    if (y[0] == cookiename):
      return y[1]
  response.close()
  return "ERROR"
  
def getMMS(url):
  ret = getMatches("http://10tv.nana10.co.il/Video/?VideoID="+url,'var sCmsVideoURL.*?"VideoLink", "(.*?)"')
  if (len(ret)>0):
    return ret[0]
  ret = getMatches("http://10tv.nana10.co.il/Video/?VideoID="+url,'var VideoLinkHQ.*?"(.*?)"')[0]
  return ret+"&ticket="+getCookie("http://10tv.nana10.co.il/Video/?VideoID="+url,"CUTicket"+url)

def getLiveMMS():
  url = str(88436);
  ret = getMatches("http://10tv.nana10.co.il/Video/?VideoID="+url,'var sCmsVideoURL.*?"(.*?)"')[0]
  return ret+"&ticket="+getCookie("http://10tv.nana10.co.il/Video/?VideoID="+url,"CUTicket"+url)

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

		
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
if (mode==None):
  getCategoryList()
elif (mode==1):
  getSeriesList()
elif (mode==2):
  getEpisodeList(url)
elif (mode==3):
   xbmc.Player().play(getMMS(url))
elif (mode==10):
   xbmc.Player().play(getLiveMMS())
  
xbmcplugin.endOfDirectory(int(sys.argv[1]))